package com.wwwarehouse.contract.orders.temp;

import android.app.Dialog;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.custom_widget.time_pick.DateAndTimePickerDialog;
import com.wwwarehouse.common.eventbus_event.ImportOrdersEvent;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.DateUtils;
import com.wwwarehouse.common.tools.DialogTools;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.contract.core.ContractConstant;
import com.wwwarehouse.contract.core.CustomOrdersMapBean;
import com.wwwarehouse.contract.core.ImportOrdersSettingInfo;

import java.util.HashMap;
import java.util.Map;

import contract.wwwarehouse.com.contract.R;
import de.greenrobot.event.EventBus;

/**
 * 订单导入设置详情
 * Created by ShineF on 2017/8/14 0014.
 */

public class ImportOrdersDetailsFragmentTemp extends BaseFragment implements View.OnClickListener, DialogTools.ConfirmListener {

    private View mRootView = null;
    private LinearLayout mLlCard = null;
    private TextView mShopName = null;
    private ImageView mIbOne = null;
    private ImageView mIbTwo = null;
    private ImageView mIbThree = null;
    private TextView mSwitchText = null;
    private TextView mAuthTime = null;
    private ImageView mImgCB = null;
    private ImportOrdersSettingInfo data = null;
    private StateLayout mStateLayout;
    private String loadStartTime = null;
    private String loadEndTime = null;
    private RadioButton mRbStartNa = null;
    private RadioButton mRbStartTime = null;
    private RadioButton mRbEndNa = null;
    private RadioButton mRbEndTime = null;
    private RadioGroup mRgStartTime = null;
    private RadioGroup mRgEndTime = null;
    private Button mBtnSubmit = null;
    private HashMap mEventMap = null;
    private TextView mTvSettingNum = null;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_import_orders_details_temp, container, false);
        return mRootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mIbOne = $(R.id.ib_one);
        mLlCard = $(R.id.ll_card);
        mIbTwo = $(R.id.ib_two);
        mTvSettingNum = $(R.id.tv_setting_number);
        mIbThree = $(R.id.ib_three);
        mStateLayout = $(R.id.sl_state);
        mRbEndNa = $(R.id.rb_end_n_a);
        mRbEndTime = $(R.id.rb_end_time);
        mRbStartNa = $(R.id.rb_start_n_a);
        mRbStartTime = $(R.id.rb_start_time);
        mImgCB = $(R.id.iv_import_orders_checked);
        mRgEndTime = $(R.id.rg_end_time);
        mBtnSubmit = $(R.id.btn_import_orders_submit);
        mRgStartTime = $(R.id.rg_start_time);
        mAuthTime = $(R.id.tv_import_orders_details_time);
        mShopName = $(R.id.tv_import_orders_details_name);
        mSwitchText = $(R.id.tv_import_orders_details_check);
        RelativeLayout mRlOne = findView(mRootView, R.id.rl_orders_1);
        RelativeLayout mRlTwo = findView(mRootView, R.id.rl_orders_2);
        RelativeLayout mRlThree = findView(mRootView, R.id.rl_orders_3);
        Drawable drawable_one = ContextCompat.getDrawable(mActivity, R.drawable.selector_radio_button);
        drawable_one.setBounds(0, 0, 60, 60);
        mRbStartNa.setCompoundDrawables(drawable_one, null, null, null);
        Drawable drawable_two = ContextCompat.getDrawable(mActivity, R.drawable.selector_radio_button);
        drawable_two.setBounds(0, 0, 60, 60);
        mRbStartTime.setCompoundDrawables(drawable_two, null, null, null);
        Drawable drawable_three = ContextCompat.getDrawable(mActivity, R.drawable.selector_radio_button);
        drawable_three.setBounds(0, 0, 60, 60);
        mRbEndNa.setCompoundDrawables(drawable_three, null, null, null);
        Drawable drawable_four = ContextCompat.getDrawable(mActivity, R.drawable.selector_radio_button);
        drawable_four.setBounds(0, 0, 60, 60);
        mRbEndTime.setCompoundDrawables(drawable_four, null, null, null);
        mBtnSubmit.setEnabled(false);
        mBtnSubmit.setSelected(false);
        mRlOne.setOnClickListener(this);
        mRlTwo.setOnClickListener(this);
        mImgCB.setOnClickListener(this);
        mRlThree.setOnClickListener(this);
        mBtnSubmit.setOnClickListener(this);
        mRbStartNa.setOnClickListener(this);
        mRbEndTime.setOnClickListener(this);
        mRbStartTime.setOnClickListener(this);
        mRgStartTime.setOnCheckedChangeListener(new MyCheckChangedListener(R.id.rg_start_time));
        mRgEndTime.setOnCheckedChangeListener(new MyCheckChangedListener(R.id.rg_end_time));
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof ImportOrdersDetailsFragmentTemp) {
            mActivity.setTitle(R.string.import_orders_setting);
        }
    }

    @Override
    public void requestDatas() {
        EventBus.getDefault().register(this);
        int type = 0;
        Bundle bundle = getArguments();
        if (null != bundle) {
            type = bundle.getInt("type");
        }
        switch (type) {
            case 1: // TODO: 2017/8/24 0024 订单导入设置任务卡片, 需要请求数据, shpID和shopName是上一个页面传过来, 等上一个页面接口做好, 目前先写死
                mStateLayout.showProgressView(true);
                Map<String, Object> map = new HashMap<>();
                map.put("shopId", "251901");
                loadData(ContractConstant.GET_IMPORT_ORDERS_INFO, map, 1);
                break;
            case 2: // TODO: 2017/8/24 0024  订单导入设置功能卡片, 直接设置, shpID和shopName是上一个页面传过来, 等上一个页面接口做好, 目前先写死
                mLlCard.setVisibility(View.VISIBLE);
                mShopName.setText(getString(R.string.shop_name));
                mIbOne.setSelected(true);
                break;
        }

    }

    public void switchButton(int what) {
        switch (what) {
            case 1:
                mIbOne.setSelected(true);
                mIbTwo.setSelected(false);
                mIbThree.setSelected(false);
                break;
            case 2:
                mIbOne.setSelected(false);
                mIbTwo.setSelected(true);
                mIbThree.setSelected(false);
                break;
            case 3:
                mIbOne.setSelected(false);
                mIbTwo.setSelected(false);
                mIbThree.setSelected(true);
                break;
        }
    }

    public int getSelectedButton() {
        if (mIbOne.isSelected()) {
            return 1;
        }
        if (mIbTwo.isSelected()) {
            return 2;
        }
        if (mIbThree.isSelected()) {
            return 3;
        }
        return 0;
    }

    public void onEventMainThread(ImportOrdersEvent event) {
        int setting = 0;
        if (event.getKey().equals("customDetails")) {
            mEventMap = event.getMap();
            for (Object key : mEventMap.keySet()) {
                if (!key.toString().equals("conditionType") && null != mEventMap.get(key) && !"".equals(mEventMap.get(key).toString())
                        && (!key.toString().equals("dateStart") && !key.toString().equals("maxPrice") && !key.toString().equals("maxQty"))) {
                    setting++;
                }
            }
        }
        mTvSettingNum.setText("已设置" + String.valueOf(setting) + "项");
    }


    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.rl_orders_1) {
            switchButton(1);

        } else if (i == R.id.rl_orders_2) {
            switchButton(2);

        } else if (i == R.id.rl_orders_3) {
            switchButton(3);
            ImportOrdersDetailsCustomFragment fragment = new ImportOrdersDetailsCustomFragment();
            Bundle bundle = new Bundle();
            if (null != data) {
//                bundle.putParcelable("data", data.getTradeAuditRule());
            }
            if (mEventMap != null) {
                bundle.putSerializable("eventData", new CustomOrdersMapBean(mEventMap));
            }
            fragment.setArguments(bundle);
            pushFragment(fragment);

        } else if (i == R.id.iv_import_orders_checked) {
            if (mImgCB.isSelected()) {
                DialogTools.getInstance().showCustomDialogPrompt(mActivity, null
                        , getString(R.string.import_orders_dialog), true, this);
            } else {
                mImgCB.setSelected(true);
                mSwitchText.setText(R.string.import_open);
            }

        } else if (i == R.id.btn_import_orders_submit) {
            if (!mImgCB.isSelected()) {
                DialogTools.getInstance().showCustomDialogPrompt(mActivity, null
                        , getString(R.string.import_orders_dialog), true, new DialogTools.ConfirmListener() {
                            @Override
                            public void setConfirmListener(Dialog dialog, View view, String input) {
                                submitEdit();
                                dialog.dismiss();
                            }
                        });
            } else {
                submitEdit();
            }

        } else if (i == R.id.rb_start_time) {
            setStartTime();

        } else if (i == R.id.rb_end_time) {
            setEndTime();

        }
    }

    public void submitEdit() {
        Map<String, Object> map = new HashMap<>();
        map.put("auditType", getSelectedButton());
        if (mRgEndTime.getCheckedRadioButtonId() == R.id.rb_end_n_a) {
            map.put("importEndTime", "");
        } else {
            map.put("importEndTime", mRbEndTime.getText());
        }
        if (mRgStartTime.getCheckedRadioButtonId() == R.id.rb_start_n_a) {
            map.put("importStartTime", "");
        } else {
            map.put("importStartTime", mRbStartTime.getText());
        }
        map.put("shopId", "251901"); // TODO: 2017/8/24 0024 上一个接口没出来, shopID先写死一个
        if (mImgCB.isSelected()) {
            map.put("tradeDown", 1);
        } else {
            map.put("tradeDown", 0);
        }
        map.put("userId", String.valueOf(123123));
        if (getSelectedButton() == 3) {
            map.put("tradeAuditRule", mEventMap);
        }
        loadData(ContractConstant.EDIT_IMPORT_ORDERS_INFO, map, 2);
    }

    @Override
    public void setConfirmListener(Dialog dialog, View view, String input) {
        mSwitchText.setText(R.string.import_close);
        dialog.dismiss();
        mImgCB.setSelected(false);
    }

    public void loadData(String url, Map<String, Object> map, int what) {
        NoHttpUtils.httpPost(url, map, new NoHttpUtils.OnResponseListener() {
            @Override
            public void onSucceed(CommonClass commonClass, int what) {
                switch (what) {
                    case 1:
                        switch (commonClass.getCode()) {
                            case "0":
                                data = JSON.parseObject(commonClass.getData().toString(), ImportOrdersSettingInfo.class);
                                setData();
                                break;
                            default:
                                mStateLayout.showNetworkView(true);
                                mStateLayout.setNetworkListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Map<String, Object> map = new HashMap<>();
                                        map.put("shopId", "251901");
                                        loadData(ContractConstant.GET_IMPORT_ORDERS_INFO, map, 1);
                                    }
                                });
                                break;
                        }
                        break;
                    case 2:
                        switch (commonClass.getCode()) {
                            case "0":

                                break;
                            default:
                                ToastUtils.showToast(commonClass.getMsg());
                                break;
                        }
                        break;
                }
            }

            @Override
            public void onFailed(String result, int what) {

            }

            @Override
            public void onFinish(int what) {

            }
        }, what);
    }

    public void setData() {
        mShopName.setText(getString(R.string.shop_name));
        mAuthTime.setText(getString(R.string.auth_text) + DateUtils.getData(String.valueOf(data.getAuthTime())));
        loadStartTime = DateUtils.getData(String.valueOf(data.getImportStartTime()));
        loadEndTime = DateUtils.getData(String.valueOf(data.getImportEndTime()));
//        switch (data.getAuditType()) {
//            case 1:
//                mIbOne.setSelected(true);
//                break;
//            case 2:
//                mIbTwo.setSelected(true);
//                break;
//            case 3:
//                mIbThree.setSelected(true);
//                break;
//        }
        mStateLayout.showContentView();
        mLlCard.setVisibility(View.VISIBLE);
    }

    private class MyCheckChangedListener implements RadioGroup.OnCheckedChangeListener {

        private int mId;

        MyCheckChangedListener(int id) {
            this.mId = id;
        }

        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            if (mId == R.id.rg_start_time) {
                if (mRbStartNa.getId() == group.getCheckedRadioButtonId()) {
                    mRbStartTime.setText(getString(R.string.edit_start_time));
                    mRbStartTime.setTextColor(ContextCompat.getColor(mActivity, R.color.common_color_c7_96999e));
                    mBtnSubmit.setSelected(getStatus());
                    mBtnSubmit.setEnabled(getStatus());
                }

            } else if (mId == R.id.rg_end_time) {
                if (mRbEndNa.getId() == group.getCheckedRadioButtonId()) {
                    mRbEndTime.setText(getString(R.string.edit_end_time));
                    mRbEndTime.setTextColor(ContextCompat.getColor(mActivity, R.color.common_color_c7_96999e));
                    mBtnSubmit.setSelected(getStatus());
                    mBtnSubmit.setEnabled(getStatus());
                }

            }
        }
    }

    /**
     * 选择时间
     */
    public void setStartTime() {
        new DateAndTimePickerDialog.Builder(mActivity)
                .setData(loadStartTime)
                .setTitle(getResources().getString(R.string.start_time))
                .setOnDateSelectedListener(new DateAndTimePickerDialog.OnDateTimeSelectedListener() {
                    @Override
                    public void onDateTimeSelected(String date) {
                        mRbStartTime.setText(date);
                        mRgStartTime.clearCheck();
                        mRbStartTime.setChecked(true);
                        mBtnSubmit.setSelected(getStatus());
                        mBtnSubmit.setEnabled(getStatus());
                    }

                    @Override
                    public void onCancel() {
                        if (mRbStartTime.getText().equals(getString(R.string.edit_start_time))) {
                            mRbStartTime.setChecked(false);
                        } else {
                            mRbStartTime.setChecked(true);
                        }
                        mBtnSubmit.setSelected(getStatus());
                        mBtnSubmit.setEnabled(getStatus());
                    }
                })
                .create()
                .show();
    }

    /**
     * 设置结束时间
     */
    public void setEndTime() {
        new DateAndTimePickerDialog.Builder(mActivity)
                .setData(loadEndTime)
                .setTitle(getResources().getString(R.string.end_time))
                .setOnDateSelectedListener(new DateAndTimePickerDialog.OnDateTimeSelectedListener() {
                    @Override
                    public void onDateTimeSelected(String date) {
                        mRbEndTime.setText(date);
                        mRgEndTime.clearCheck();
                        mRbEndTime.setChecked(true);
                        mBtnSubmit.setSelected(getStatus());
                        mBtnSubmit.setEnabled(getStatus());
                    }

                    @Override
                    public void onCancel() {
                        if (mRbEndTime.getText().equals(getString(R.string.edit_end_time))) {
                            mRbEndTime.setChecked(false);
                        } else {
                            mRbEndTime.setChecked(true);
                        }
                        mBtnSubmit.setSelected(getStatus());
                        mBtnSubmit.setEnabled(getStatus());
                    }
                })
                .create()
                .show();

    }

    public boolean getStatus() {
        return (mRbStartTime.isChecked() || mRbStartNa.isChecked()) && (mRbEndTime.isChecked() || mRbEndNa.isChecked());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
